package com.stiff.web.interceptor;

import com.stiff.common.utils.CookieUtils;
import com.stiff.web.bean.User;
import com.stiff.web.service.PropertieService;
import com.stiff.web.service.UserService;
import com.stiff.web.thread.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserLoginHandlerInterceptor implements HandlerInterceptor {
    public static final String COOKIE_NAME = "TT_TOKEN";
    @Autowired
    private PropertieService propertieService;
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        UserThreadLocal.set(null);//清空当前线程中的user对象
        String url = propertieService.TAOTAO_SSO_URL+"/user/login.html";
        String token = CookieUtils.getCookieValue(request,COOKIE_NAME);
        if(StringUtils.isEmpty(token)){
            response.sendRedirect(url);
            return false;
        }
        User user = this.userService.queryUserByToken(token);
        if(null==user){
            response.sendRedirect(url);
            return false;
        }
        UserThreadLocal.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mv) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }
}
